package org.kineticsproject.application;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.jfree.chart.JFreeChart;
import org.kineticsproject.visualizations.HeartRatePieChart;
import org.kineticsproject.visualizations.VisualizationGenerator;

import data.Exercise;
import data.State;


public class OpenViewAction extends Action implements ISelectionListener {
	
	private final IWorkbenchWindow window;
	private int instanceNum = 0;
	private final String viewId;
	private State state;
	
	//private Exercise exerciseSelected;
	//private JFreeChart chartHR;
	
	public OpenViewAction(IWorkbenchWindow window, String label, String viewId) {
		this.window = window;
		this.viewId = viewId;
        setText(label);
        // The id is used to refer to the action in a menu or toolbar
		setId(ICommandIds.CMD_OPEN);
        // Associate the action with a pre-defined command, to allow key bindings.
		setActionDefinitionId(ICommandIds.CMD_OPEN);
		setImageDescriptor(org.kineticsproject.application.Activator.getImageDescriptor("/icons/sample2.gif"));
	
		window.getSelectionService().addSelectionListener(this);
		setEnabled(false);
		state = State.getInstance();
	}
	
	public void run() {
		if(window != null) {	
			try {
				

				window.getActivePage().showView(viewId, Integer.toString(instanceNum++), IWorkbenchPage.VIEW_ACTIVATE);
				window.getActivePage().showView("org.kineticsproject.application.xytimeseriesview","secondary",IWorkbenchPage.VIEW_ACTIVATE);
								
							
			} catch (PartInitException e) {
				MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e.getMessage());
			}
		}
	}
	
	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incomingSelection) {
		
		IStructuredSelection selection;
		
		if (incomingSelection instanceof IStructuredSelection)
		{
			selection = (IStructuredSelection) incomingSelection;
			if (1 == selection.size() && selection.getFirstElement() instanceof ExerciseNavigationView.TreeObject)
			{
				
				setEnabled(true);
				state.setActiveExercise(((ExerciseNavigationView.TreeObject)selection.getFirstElement()).getExercise());
					

				}
			else
			{
				setEnabled(false);
			}
		}
		else
		{
			setEnabled(false);
		}
			
		}
		
		
	


	public void dispose()
	{
		// remove SelectionListener for PopulationNavigation selections
		//getSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
		window.getSelectionService().removeSelectionListener(this);
	}
	
	
}
